package database

func ListGroupPermissionsByResourceType(resourceType string) ([]GroupPermission, error) {
	var groupPermissions []GroupPermission

	err := db.Where("resource_type = ?", resourceType).Find(&groupPermissions).Error
	if err != nil {
		return nil, err
	}

	return groupPermissions, nil
}

func ListUserPermission(userId, resourceId int64, groupIds []int64, resourceType string) ([]string, error) {
	var groupOperationType []string
	err1 := db.Raw("select operation_type from group_permission where resource_type = ? and resource_id = ? and group_id in ?",
		resourceType, resourceId, groupIds).Find(&groupOperationType).Error
	if err1 != nil {
		return nil, err1
	}

	var userOperationType []string
	err2 := db.Raw("select operation_type from user_permission where resource_type = ? and resource_id = ? and user_id = ?",
		resourceType, resourceId, userId).Find(&userOperationType).Error
	if err2 != nil {
		return nil, err2
	}

	for _, s := range userOperationType {
		groupOperationType = append(groupOperationType, s)
	}

	return groupOperationType, nil
}

func ListResourceIdByGroupIds(groupIds []int64, resourceType string) []int64 {
	var resourceIDs []int64

	// 查询资源ID
	db.Table("group_permission").
		Select("DISTINCT resource_id").
		Where("group_id IN (?) AND resource_type = ?", groupIds, resourceType).
		Pluck("resource_id", &resourceIDs)

	return resourceIDs
}

func ListResourceIdByUserId(userId int64, resourceType string) []int64 {
	var resourceIDs []int64

	// 查询资源ID
	db.Table("user_permission").
		Select("DISTINCT resource_id").
		Where("user_id = ? AND resource_type = ?", userId, resourceType).
		Pluck("resource_id", &resourceIDs)

	return resourceIDs
}

func ListPermissionByGroupIds(groupIds []int64, resourceType string) []GroupPermission {
	var permissions []GroupPermission

	// 查询权限信息
	db.Table("group_permission").
		Where("resource_id IN (?) AND group_id IN (?) AND resource_type = ?", []int64{-1, -2, -3}, groupIds, resourceType).
		Find(&permissions)

	return permissions
}

func ListPermissionByUserId(userId int64, resourceType string) []UserPermission {
	var permissions []UserPermission

	// 查询权限信息
	db.Table("user_permission").
		Where("resource_id IN (?) AND user_id = ? AND resource_type = ?", []int64{-1, -2, -3}, userId, resourceType).
		Find(&permissions)

	return permissions
}
